
package com.example.learningnote.giftbox;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.learningnote.R;

import java.util.List;

/**
 * RecyclerView 适配器，显示单页礼物（两行四列）
 * 适配器层（GiftAdapter）
 */
public class GiftAdapter extends RecyclerView.Adapter<GiftAdapter.GiftViewHolder> {
    private List<Gift> gifts; // 单页礼物列表（最多8个）
    private String selectedGiftId; // 当前选中礼物 ID
    private OnGiftClickListener onGiftClickListener; // 点击监听器

    public GiftAdapter(List<Gift> gifts) {
        this.gifts = gifts;
    }

    /**
     * 更新礼物列表
     */
    public void updateGifts(List<Gift> gifts) {
        this.gifts = gifts;
        notifyDataSetChanged();
    }

    /**
     * 更新选中状态
     */
    public void updateSelectedGiftId(String selectedGiftId) {
        this.selectedGiftId = selectedGiftId;
        notifyDataSetChanged();
    }

    /**
     * 设置点击监听器
     */
    public void setOnGiftClickListener(OnGiftClickListener listener) {
        this.onGiftClickListener = listener;
    }

    public interface OnGiftClickListener {
        void onGiftClick(Gift gift);
    }

    @NonNull
    @Override
    public GiftViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_gift, parent, false);
        return new GiftViewHolder(view);
    }

    // 绑定数据
    @Override
    public void onBindViewHolder(@NonNull GiftViewHolder holder, int position) {
        if (position < gifts.size()) {
            Gift gift = gifts.get(position);
            holder.textView.setText(gift.getGiftName());
            boolean isSelected = gift.getId().equals(selectedGiftId);
            holder.itemView.setSelected(isSelected); // 设置选中状态（边框）
            holder.itemView.setOnClickListener(v -> {
                if (onGiftClickListener != null) {
                    onGiftClickListener.onGiftClick(gift);
                }
            });
        } else {
            // 空位显示空白
            holder.textView.setText("");
            holder.itemView.setSelected(false);
            holder.itemView.setOnClickListener(null);

        }
    }

    @Override
    public int getItemCount() {
        return 8; // 固定8个位置（两行四列）
    }

    static class GiftViewHolder extends RecyclerView.ViewHolder {
        TextView textView;

        GiftViewHolder(View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.tvGiftName);
        }
    }
}

